package org.example;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

/**
 * @author Anhui OuYang
 * @version 1.0
 * TCP客户端
 **/
public class TCPDemoClient {
    public static void main(String[] args) {
        try {
            //创建Socket，并且连接服务器127.0.0.0:10086的服务器上
            Socket socket = new Socket("127.0.0.1", 10086);

            //获取网络输出流
            OutputStream outputStream = socket.getOutputStream();

            //发送数据给服务端
            byte[] bytes = "今天真漂亮\r\n啦啦啦".getBytes(StandardCharsets.UTF_8);
            outputStream.write(bytes, 0, bytes.length);
            //告知服务器，数据发送结束
            socket.shutdownOutput();

            //等待获取服务器发送过来的处理成功消息
            InputStream inputStream = socket.getInputStream();
            byte[] bytes1 = new byte[1024];
            int s;
            while ((s = inputStream.read(bytes1)) != -1) {
                System.out.print(new String(bytes1, 0, s, StandardCharsets.UTF_8));
            }

            //关闭Socket，关闭这个系统会默认先关闭outputStream
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}